var cacheStr = window.sessionStorage.getItem("cache"),
    oneLoginStr = window.sessionStorage.getItem("oneLogin");
layui.use(['form', 'jquery', 'element', "layer"], function () {
    var form = layui.form,
        $ = layui.jquery,
        element = layui.element,
        layer = parent.layer === undefined ? layui.layer : top.layer;

    //判断是否web端打开
    if (!/http(s*):\/\//.test(location.href)) {
        layer.alert("请先将项目部署后再进行访问");
    } else {    //判断是否处于锁屏状态【如果关闭以后则未关闭浏览器之前不再显示】
        if (window.sessionStorage.getItem("lockcms") !== "true" && window.sessionStorage.getItem("showNotice") !== "true") {
            //showNotice();
        }
    }

    var xxx = getUrlParam('culture');

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }

    var noticeTitle = '系统公告';
    var noticeMsg1 = 'LViewLMS学习培训管理系统正式上线啦，界面采用贤心最新版layui及马哥的layuicms！';
    var noticeMsg2 = '使用中任何异常，请点击页面下方联系我们哦！';
    var noticeBtn = '火速围观';
    var noticeTips = '系统公告躲在了这里';
    var unlock = '解锁';
    var unlockPlaceholder = '请输入密码解锁..';
    var unlockMemo = '解锁密码同登录密码';
    var unlockMsg = '密码错误，请重新输入！';
    var functionSet = '功能设定';
    var tabSession = '开启Tab缓存';
    var tabRefresh = 'Tab切换刷新';
    var singleSign = '单一登陆';
    var close = '关';
    var open = '开';
    var finish = '设定完成';
    var cancle = '朕再想想';
    var tabSessionMemo = '开启后刷新页面不关闭打开的Tab页';
    var tabRefreshMemo = '开启后切换窗口刷新当前页面';
    var singleSignMemo = '开启后不可同时多个地方登录';
    var changeSkin = '更换皮肤';
    var defaultSkin = '默认';
    var orangeSkin = '橙色';
    var blueSkin = '蓝色';
    var customSkin = '自定义';
    var topColor = '顶部颜色';
    var leftColor = '左侧颜色';
    var topMenuColor = '顶部菜单按钮';

    if (xxx == 'vi') {
        noticeTitle = 'Thông báo hệ thống';
        noticeMsg1 = 'LViewLMS hệ thống quản lý đào tạo chính thức hoạt động, giao diện với phiên bản mới nhất của xian xin layui và ma yuicms!';
        noticeMsg2 = 'Sử dụng bất kỳ ngoại lệ, hãy nhấp vào dưới trang để liên hệ với chúng tôi!';
        noticeBtn = 'Xem nhanh đi';
        noticeTips = 'Thông báo ở đây';
        unlock = 'Mở ra';
        unlockMemo = 'Mật khẩu mở khóa giống như mật khẩu đăng nhập';
        unlockPlaceholder = 'Nhập mật khẩu mở khóa';
        unlockMsg = 'Mật khẩu sai, xin vui lòng nhập lại!';
        functionSet = 'Thiết lập Chức năng';
        tabSession = 'Mở Cache';
        tabRefresh = 'Để tải';
        singleSign = 'Đổ bộ';
        close = 'nhốt';
        open = 'Mở';
        finish = 'Hoàn thành';
        cancle = 'Hủy bỏ';
        tabSessionMemo = 'Không đóng mở trang';
        tabRefreshMemo = 'Làm mới trang';
        singleSignMemo = 'Không thể đăng nhập ở những nơi khác nhau';
        changeSkin = 'Thay thế da';
        defaultSkin = 'Mặc định';
        orangeSkin = 'Màu CAM';
        blueSkin = 'Màu xanh';
        customSkin = 'ĐịnhNghĩa';
        topColor = 'Màu trên cùng';
        leftColor = 'Màu bên trái';
        topMenuColor = 'Nút trên trình đơn';
    }

    if (xxx == 'en') {
        noticeTitle = 'System Notice';
        noticeMsg1 = 'The LViewLMS learning and training management system was officially launched, and the interface adopted the latest version of LayUI of Xian Xin and LayuicMS of Ma';
        noticeMsg2 = 'If there is any exception, please click the bottom of the page to contact us!';
        noticeBtn = 'Rushing onlookers';
        noticeTips = 'System announcements are hiding here';
        unlock = 'Unlock';
        unlockMemo = 'Password is the same as login password';
        unlockPlaceholder = 'Enter unlock password';
        unlockMsg = 'Password error,please enter again!';
        functionSet = 'Function Set';
        tabSession = 'Cache';
        tabRefresh = 'Tab refresh';
        singleSign = 'Single Sign';
        close = 'Close';
        open = 'Open';
        finish = 'Setup Completed';
        cancle = 'Cancle';
        tabSessionMemo = 'Refresh without closing the open';
        tabRefreshMemo = 'Refresh current with the toggle';
        singleSignMemo = 'Cannot log in different place';
        changeSkin = 'Change Skin';
        defaultSkin = 'Default';
        orangeSkin = 'Orange';
        blueSkin = 'Blue';
        customSkin = 'Custom';
        topColor = 'Top Color';
        leftColor = 'Left Color';
        topMenuColor = 'Top menu button';
    }


    //公告层
    function showNotice() {
        layer.open({
            type: 1,
            title: noticeTitle,
            area: '300px',
            shade: 0.8,
            id: 'LAY_layuipro',
            btn: [noticeBtn],
            moveType: 1,
            content: '<div style="padding:15px 20px; text-align:justify; line-height: 22px; text-indent:2em;border-bottom:1px solid #e2e2e2;">' +
                '<p>' + noticeMsg1 + '</p>' +
                '<p>' + noticeMsg2 + '</p></div>',
            success: function (layero) {
                var btn = layero.find('.layui-layer-btn');
                btn.css('text-align', 'center');
                btn.on("click", function () {
                    tipsShow();
                });
            },
            cancel: function (index, layero) {
                tipsShow();
            }
        });
    }
    function tipsShow() {
        window.sessionStorage.setItem("showNotice", "true");
        if ($(window).width() > 432) {  //如果页面宽度不足以显示顶部“系统公告”按钮，则不提示
            layer.tips(noticeTips, '#userInfo', {
                tips: 3,
                time: 1000
            });
        }
    }
    $(".showNotice").on("click", function () {
        showNotice();
    });

    //切换语言
    $(".mutlilanguage dd").on("click", function () {
        var url = window.location;
        var chooseLanguage = $(this).find('a').attr('data-id');
        var chooseLanuageHtml = $(this).find('a').attr('data-text');
        var index = url.toString().indexOf('?');
        if (index > 0) {
            url = url.toString().substr(0, index - 1);
        }
        url = url + "?culture=" + chooseLanguage;
        window.sessionStorage.setItem("Language", chooseLanuageHtml);
        window.location.href = url;
    });

    var language = window.sessionStorage.getItem("Language");
    if (language == null)
        $("#DisplayLanuage").append('<cite>请选择语言</cite>');
    else
        $("#DisplayLanuage").append('<cite>' + language + '</cite>');
    console.log(language);

    //锁屏
    function lockPage() {
        layer.open({
            title: false,
            type: 1,
            content: '<div class="admin-header-lock" id="lock-box">' +
                '<div class="admin-header-lock-img"><img src="' + window.sessionStorage.getItem('userFace') + '" class="userAvatar"/></div>' +
                '<div class="admin-header-lock-name" id="lockUserName">' + window.sessionStorage.getItem('userName') + '</div>' +
                '<div class="input_btn">' +
                '<input type="password" class="admin-header-lock-input layui-input" autocomplete="off" placeholder="' + unlockPlaceholder + '" name="lockPwd" id="lockPwd" />' +
                '<button class="layui-btn" id="unlock">' + unlock + '</button>' +
                '</div>' +
                '<p>' + unlockMemo + '</p>' +
                '</div>',
            closeBtn: 0,
            shade: 0.9,
            success: function () {
                //判断是否设置过头像，如果设置过则修改顶部、左侧和个人资料中的头像，否则使用默认头像
                if (window.sessionStorage.getItem('userFace') && $(".userAvatar").length > 0) {
                    $(".userAvatar").attr("src", window.sessionStorage.getItem('userFace'));
                }
            }
        });
        $(".admin-header-lock-input").focus();
    }
    $(".lockcms").on("click", function () {
        window.sessionStorage.setItem("lockcms", true);
        lockPage();
    });
    // 判断是否显示锁屏
    if (window.sessionStorage.getItem("lockcms") === "true") {
        lockPage();
    }
    // 解锁
    $("body").on("click", "#unlock", function () {
        if ($(this).siblings(".admin-header-lock-input").val() === '') {
            layer.msg(unlockPlaceholder);
            $(this).siblings(".admin-header-lock-input").focus();
        } else {
            var userPsd = '';
            var lockInput = $(this).siblings(".admin-header-lock-input").val();
            $.ajax({
                type: 'POST',
                url: '/Manager/GetCurrManagerInfo/',
                data: { psd: lockInput },
                dataType: "json",
                headers: {
                    "X-CSRF-TOKEN-Gerald": $("input[name='AntiforgeryKey_Gerald']").val()
                },
                success: function (res) {
                    if (res.ResultCode == 0) {
                        window.sessionStorage.setItem("lockcms", false);
                        $(this).siblings(".admin-header-lock-input").val('');
                        layer.closeAll("page");
                    } else {
                        layer.msg(unlockMsg);
                        $(this).siblings(".admin-header-lock-input").val('').focus();
                    }
                }
            });

        }
    });
    $(document).on('keydown', function (event) {
        var event2 = event || window.event;
        if (event2.keyCode === 13) {
            $("#unlock").click();
        }
    });

    //退出
    $(".signOut").click(function () {
        window.sessionStorage.removeItem("menu");
        menu = [];
        window.sessionStorage.removeItem("curmenu");
    });

    //功能设定
    $(".functionSetting").click(function () {
        layer.open({
            title: functionSet,
            area: ["380px", "280px"],
            type: "1",
            content: '<div class="functionSrtting_box">' +
                '<form class="layui-form">' +
                '<div class="layui-form-item">' +
                '<label class="layui-form-label">' + tabSession + '</label>' +
                '<div class="layui-input-block">' +
                '<input type="checkbox" name="cache" lay-skin="switch" lay-text="' + open + '|' + close + '">' +
                '<div class="layui-word-aux">' + tabSessionMemo + '</div>' +
                '</div>' +
                '</div>' +
                '<div class="layui-form-item">' +
                '<label class="layui-form-label">' + tabRefresh + '</label>' +
                '<div class="layui-input-block">' +
                '<input type="checkbox" name="changeRefresh" lay-skin="switch" lay-text="' + open + '|' + close + '">' +
                '<div class="layui-word-aux">' + tabRefreshMemo + '</div>' +
                '</div>' +
                '</div>' +
                '<div class="layui-form-item">' +
                '<label class="layui-form-label">' + singleSign + '</label>' +
                '<div class="layui-input-block">' +
                '<input type="checkbox" name="oneLogin" lay-filter="multipleLogin" lay-skin="switch" lay-text="' + open + '|' + close + '">' +
                '<div class="layui-word-aux">' + singleSignMemo + '</div>' +
                '</div>' +
                '</div>' +
                '<div class="layui-form-item skinBtn">' +
                '<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="" lay-filter="settingSuccess">' + finish + '</a>' +
                '<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-primary" lay-submit="" lay-filter="noSetting">' + cancle + '</a>' +
                '</div>' +
                '</form>' +
                '</div>',
            success: function (index, layero) {
                //如果之前设置过，则设置它的值
                $(".functionSrtting_box input[name=cache]").prop("checked", cacheStr === "true" ? true : false);
                $(".functionSrtting_box input[name=changeRefresh]").prop("checked", changeRefreshStr === "true" ? true : false);
                $(".functionSrtting_box input[name=oneLogin]").prop("checked", oneLoginStr === "true" ? true : false);
                //设定
                form.on("submit(settingSuccess)", function (data) {
                    window.sessionStorage.setItem("cache", data.field.cache === "on" ? "true" : "false");
                    window.sessionStorage.setItem("changeRefresh", data.field.changeRefresh === "on" ? "true" : "false");
                    window.sessionStorage.setItem("oneLogin", data.field.oneLogin === "on" ? "true" : "false");
                    window.sessionStorage.removeItem("menu");
                    window.sessionStorage.removeItem("curmenu");
                    location.reload();
                    return false;
                });
                //取消设定
                form.on("submit(noSetting)", function () {
                    layer.closeAll("page");
                });
                //单一登陆提示
                form.on('switch(multipleLogin)', function (data) {
                    layer.tips('温馨提示：此功能需要开发配合，所以没有功能演示，敬请谅解', data.othis, { tips: 1 });
                });
                form.render();  //表单渲染
            }
        });
    });

    //判断是否修改过系统基本设置，去显示底部版权信息
    if (window.sessionStorage.getItem("systemParameter")) {
        systemParameter = JSON.parse(window.sessionStorage.getItem("systemParameter"));
        $(".footer p span").text(systemParameter.powerby);
    }

    //更换皮肤
    function skins() {
        var skin = window.sessionStorage.getItem("skin");
        if (skin) {  //如果更换过皮肤
            if (window.sessionStorage.getItem("skinValue") !== customSkin) {
                $("body").addClass(window.sessionStorage.getItem("skin"));
            } else {
                $(".layui-layout-admin .layui-header").css("background-color", skin.split(',')[0]);
                $(".layui-bg-black").css("background-color", skin.split(',')[1]);
                $(".hideMenu").css("background-color", skin.split(',')[2]);
            }
        }
    }
    skins();
    $(".changeSkin").click(function () {
        layer.open({
            title: changeSkin,
            area: ["310px", "280px"],
            type: "1",
            content: '<div class="skins_box">' +
                '<form class="layui-form">' +
                '<div class="layui-form-item">' +
                '<input type="radio" name="skin" value="' + defaultSkin + '" title="' + defaultSkin + '" lay-filter="default" checked="">' +
                '<input type="radio" name="skin" value="' + orangeSkin + '" title="' + orangeSkin + '" lay-filter="orange">' +
                '<input type="radio" name="skin" value="' + blueSkin + '" title="' + blueSkin + '" lay-filter="blue">' +
                '<input type="radio" name="skin" value="' + customSkin + '" title="' + customSkin + '" lay-filter="custom">' +
                '<div class="skinCustom">' +
                '<input type="text" class="layui-input topColor" name="topSkin" placeholder="' + topColor + '" />' +
                '<input type="text" class="layui-input leftColor" name="leftSkin" placeholder="' + leftColor + '" />' +
                '<input type="text" class="layui-input menuColor" name="btnSkin" placeholder="' + topMenuColor + '" />' +
                '</div>' +
                '</div>' +
                '<div class="layui-form-item skinBtn">' +
                '<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="" lay-filter="changeSkin">' + finish + '</a>' +
                '<a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-primary" lay-submit="" lay-filter="noChangeSkin">' + cancle + '</a>' +
                '</div>' +
                '</form>' +
                '</div>',
            success: function (index, layero) {
                var skin = window.sessionStorage.getItem("skin");
                if (window.sessionStorage.getItem("skinValue")) {
                    $(".skins_box input[value=" + window.sessionStorage.getItem("skinValue") + "]").attr("checked", "checked");
                }
                console.log(".skins_box input[value=" + customSkin + "]");
                if ($(".skins_box input[value=" + customSkin + "]").attr("checked")) {
                    $(".skinCustom").css("visibility", "inherit");
                    $(".topColor").val(skin.split(',')[0]);
                    $(".leftColor").val(skin.split(',')[1]);
                    $(".menuColor").val(skin.split(',')[2]);
                }
                form.render();
                $(".skins_box").removeClass("layui-hide");
                $(".skins_box .layui-form-radio").on("click", function () {
                    var skinColor;
                    if ($(this).find("div").text() === orangeSkin) {
                        skinColor = "orange";
                    } else if ($(this).find("div").text() === blueSkin) {
                        skinColor = "blue";
                    } else if ($(this).find("div").text() === defaultSkin) {
                        skinColor = "";
                    }
                    console.log($(this).find("div").text());
                    console.log(customSkin);
                    if ($(this).find("div").text() !== customSkin) {
                        $(".topColor,.leftColor,.menuColor").val('');
                        $("body").removeAttr("class").addClass("main_body " + skinColor + "");
                        $(".skinCustom").removeAttr("style");
                        $(".layui-bg-black,.hideMenu,.layui-layout-admin .layui-header").removeAttr("style");
                    } else {
                        $(".skinCustom").css("visibility", "inherit");
                    }
                });
                var skinStr, skinColor;
                $(".topColor").blur(function () {
                    $(".layui-layout-admin .layui-header").css("background-color", $(this).val() + " !important");
                });
                $(".leftColor").blur(function () {
                    $(".layui-bg-black").css("background-color", $(this).val() + " !important");
                });
                $(".menuColor").blur(function () {
                    $(".hideMenu").css("background-color", $(this).val() + " !important");
                });

                form.on("submit(changeSkin)", function (data) {
                    if (data.field.skin !== customSkin) {
                        if (data.field.skin === orangeSkin) {
                            skinColor = "orange";
                        } else if (data.field.skin === blueSkin) {
                            skinColor = "blue";
                        } else if (data.field.skin === defaultSkin) {
                            skinColor = "";
                        }
                        window.sessionStorage.setItem("skin", skinColor);
                    } else {
                        skinStr = $(".topColor").val() + ',' + $(".leftColor").val() + ',' + $(".menuColor").val();
                        window.sessionStorage.setItem("skin", skinStr);
                        $("body").removeAttr("class").addClass("main_body");
                    }
                    window.sessionStorage.setItem("skinValue", data.field.skin);
                    layer.closeAll("page");
                });
                form.on("submit(noChangeSkin)", function () {
                    $("body").removeAttr("class").addClass("main_body " + window.sessionStorage.getItem("skin") + "");
                    $(".layui-bg-black,.hideMenu,.layui-layout-admin .layui-header").removeAttr("style");
                    skins();
                    layer.closeAll("page");
                });
            },
            cancel: function () {
                $("body").removeAttr("class").addClass("main_body " + window.sessionStorage.getItem("skin") + "");
                $(".layui-bg-black,.hideMenu,.layui-layout-admin .layui-header").removeAttr("style");
                skins();
            }
        });
    });

});